/*
 * @Descripttion:userStore
 * @LastEditors: xueyc
 * @LastEditTime: 2024-08-16 22:46:14
 */
import { defineStore } from 'pinia'
import Cookies_Token from '@/utils/cache/cookies/token'
import { userStroe_Inf, user_Inf } from './index.d'
import router from '@/router'
import Dile_APi from '@/api'
import Dile_Constants from '@/utils/constants/app'
import { object_Inf } from '@/utils/typings/index.type'
import Dile_Methods from '@/utils/methods'

let tokenCookies = new Cookies_Token()

let useUserStore = defineStore('userStore', {
  state: (): userStroe_Inf => ({
    token: tokenCookies.get(),
    //用户信息
    userInfo: {
      id: 0, //用户名主键
      account: '', //账号
      userName: '', //用户名
      headImg: '' //头像
    },
    //用户角色信息
    userRoleInfo: {
      roleId: 0, //角色组件
      powerSet: {} //权限设置
    }
  }),
  //开启持久化
  persist: {
    enabled: true
  },
  actions: {
    /**
     * @Author: xzh
     * @Descripttion: 登录
     * @Param:
     * @param {user_Inf} userInfo-用户信息
     */
    async login(userInfo: user_Inf) {
      // let { token } = await Dile_APi.login(userInfo);
      let token = Dile_Methods.newGuid()
      //cookie设置token
      tokenCookies.set(token)
      this.token = token
    },
    /**
     * @Author: xzh
     * @Descripttion: 根据token获取用户信息
     * @Param:
     */
    async getUserInfo(): Promise<user_Inf> {
      //let data = await Dile_APi.getUserInfo()
      let data: object_Inf = {
        id: Dile_Methods.newGuid(),
        account: 'admin',
        name: 'admin',
        extJson: JSON.stringify({
          powerSetJson: {}
        }),
        headImg: ''
      }
      let { id, account, headImg, name, extJson } = data
      Object.assign(this.userInfo, {
        id,
        account,
        userName: name,
        headImg
      })
      let { modulePowerArr } = JSON.parse(extJson.powerSetJson || '{}'),
        //管理员-不启用权限设置
        isEnable = account != 'admin'
      this.userRoleInfo = {
        isEnable,
        powerSet: {
          modulePowerArr: Dile_Methods.uniqueArr(
            [
              ...(modulePowerArr || []),
              ...Dile_Constants.fixModuleArr.map((module: string) => ({
                module
              }))
            ],
            'module'
          )
        }
      }
      return data
    },
    /**
     * @Author: xzh
     * @Descripttion:退出登录
     * @Param:
     */
    async logout() {
      let { account } = this.userInfo
      await Dile_APi.logout(account)
      tokenCookies.removeAll()
      //退出至登录页
      router.push('/login')
    },
    /**
     * @Author: xzh
     * @Descripttion: 移除token
     * @Param:
     */
    resetToken() {
      tokenCookies.remove()
      this.token = ''
    }
  }
})

export default useUserStore
